package phone.qyg.com.qyg.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;
import com.zfdang.multiple_images_selector.ImagesSelectorActivity;
import com.zfdang.multiple_images_selector.SelectorSettings;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.utils.AppHttpRequest;
import phone.qyg.com.qyg.utils.PopuTypeSelectState;

@ContentView(R.layout.activity_volunteer_reg)
public class VolunteerRegActivity extends BaseActivity {
    final int DATE_DIALOG = 1;
    final int REQUEST_CODE = 1131;
    int mYear = ApplicationConfig.YEAR;

    int mMonth = ApplicationConfig.MONTH;

    int mDay = ApplicationConfig.DAY;
    @ViewInject(R.id.back)
    TextView back;
    @ViewInject(R.id.iv_head)
    ImageView iv_head;
    @ViewInject(R.id.tv_code)
    TextView tv_code;
    @ViewInject(R.id.et_phone)
    EditText et_phone;
    @ViewInject(R.id.ll_bir)
    LinearLayout ll_bir;
    @ViewInject(R.id.tv_education)
    TextView tv_education;
    @ViewInject(R.id.tv_time)
    TextView tv_time;
    @ViewInject(R.id.et_name)
            EditText et_name;
    @ViewInject(R.id.rg)
    RadioGroup rg;
    @ViewInject(R.id.rb_man)
    RadioButton rb_man;
    @ViewInject(R.id.rb_women)
            RadioButton rb_women;
    @ViewInject(R.id.rg_type)
    RadioGroup rg_type;
    @ViewInject(R.id.rb_gr)
    RadioButton rb_gr;
    @ViewInject(R.id.rb_td)
    RadioButton rb_td;
    @ViewInject(R.id.et_card)
            EditText et_card;
    @ViewInject(R.id.et_code)
            EditText et_code;
    @ViewInject(R.id.et_mail)
            EditText et_mail;
    @ViewInject(R.id.tv_political)
            TextView tv_political;
    @ViewInject(R.id.tv_job)
            TextView tv_job;
    @ViewInject(R.id.et_adr)
            EditText et_adr;
    @ViewInject(R.id.et_hoby)
            EditText et_hoby;
    @ViewInject(R.id.et_content)
            EditText et_content;
    @ViewInject(R.id.send_discuss)
    RelativeLayout send_discuss;
    @ViewInject(R.id.ll_type)
    LinearLayout ll_type;
    int i = 60;
    List<String> tranImgs = new ArrayList<String>();
    Base eduLevelTheme,politicalLevel,jobLevel;//学历状态
    List<Base> eduMap = new ArrayList<>();
    List<Base> politicalMap = new ArrayList<>();
    List<Base> jobMap = new ArrayList<>();
    String format,appInfo;
    ProgressDialog dialog;
    @Override
    public void initSucessView() {
        appInfo = SharePrefUtil.getString(SharePrefUtil.KEY.APP_INFO,"");

        if(!CommonUtil.isRequestStr(appInfo)){
            AppHttpRequest.httpAppInfo(new AppHttpRequest.OnAppHttpListener() {
                @Override
                public void onAppHttpState(boolean isState, String result) {
                    if(isState){
                        appInfo = result;
                    }
                }
            });
        }

        format = JSONTool.requestJSONfindName(JSONTool.jsonDefaluTranString(appInfo,JSONTool.Enum.MOBILE_FORMAT),
                JSONTool.Enum.FORMAT);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        int type = getIntent().getIntExtra("type", 0);
        dialog = new ProgressDialog(this);
        if(type==1){
            ll_type.setVisibility(View.GONE);
            back.setText("人才报名");
        }else{
            ll_type.setVisibility(View.VISIBLE);
            back.setText("志愿者报名");
        }
        //学历
        eduMap.add(new Base(1,1,"小学"));
        eduMap.add(new Base(1,2,"初中"));
        eduMap.add(new Base(1,3,"高中"));
        eduMap.add(new Base(1,4,"专科"));
        eduMap.add(new Base(1,5,"本科"));
        eduMap.add(new Base(1,6,"硕士"));
        eduMap.add(new Base(1,7,"博士"));
        //政治面貌
        politicalMap.add(new Base(1,1,"中共党员"));
        politicalMap.add(new Base(1,2,"民主党派"));
        politicalMap.add(new Base(1,3,"群众"));
        politicalMap.add(new Base(1,4,"其他"));
        //职业
        jobMap.add(new Base(1,1,"国家公务人员"));
        jobMap.add(new Base(1,2,"专业技术人员"));
        jobMap.add(new Base(1,3,"职员"));
        jobMap.add(new Base(1,4,"企业管理人员"));
        jobMap.add(new Base(1,5,"工人"));
        jobMap.add(new Base(1,6,"农民"));
        jobMap.add(new Base(1,7,"学生"));
        jobMap.add(new Base(1,8,"教师"));
        jobMap.add(new Base(1,9,"现役军人"));
        jobMap.add(new Base(1,10,"自由职业者"));
        jobMap.add(new Base(1,11,"个体经营者"));
        jobMap.add(new Base(1,12,"无业人员"));
        jobMap.add(new Base(1,13,"退（离）休人员"));
        jobMap.add(new Base(1,14,"其他"));
    }

    @Override
    public void initViewHandler() {
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.rb_man:
                        rb_women.setChecked(false);
                        break;
                    case R.id.rb_women:
                        rb_man.setChecked(false);
                        break;
                }
            }
        });
        rg_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
                switch (checkId){
                    case R.id.rb_gr:
                        rb_td.setChecked(false);
                        break;
                    case R.id.rb_td:
                        rb_gr.setChecked(false);
                        break;
                }
            }
        });
    }
    @Event(value = {R.id.back,R.id.iv_head,R.id.tv_code,R.id.ll_bir,R.id.tv_education,R.id.tv_political,
    R.id.tv_job,R.id.send_discuss})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.iv_head:
                addPath();
                break;
            case R.id.tv_code:
                if(et_phone.getText().toString().trim().isEmpty()){
                    PromptManager.showToast("手机号码不能为空");
                }else if(et_phone.getText().toString().trim().length()!=11){
                    PromptManager.showToast("手机号码长度为11位");
                }else{
                    sendMsg();
                    // 3.倒计时
                    tv_code.setClickable(false);
                    tv_code.setText("重新发送("+i+")");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (; i > 0; i--) {
                                handler.sendEmptyMessage(-9);
                                if (i <= 0) {
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            handler.sendEmptyMessage(-8);
                        }
                    }).start();
                }
                break;
            case R.id.ll_bir:
                //生日
                showDialog(DATE_DIALOG);
                break;
            case R.id.tv_education:
                PopuTypeSelectState.setShowData(this,eduMap, new PopuTypeSelectState.OnAlertOnClick() {
                    @Override
                    public void onClick(Base theme, int dataType, AlertDialog showAlert) {
                        if(theme.type == 1){
                            eduLevelTheme = theme;
                            tv_education.setText(theme.title);
                        }

                        dismissDialog(showAlert);
                    }
                });
                break;
            case R.id.tv_political:
                PopuTypeSelectState.setShowData(this,politicalMap, new PopuTypeSelectState.OnAlertOnClick() {
                    @Override
                    public void onClick(Base theme, int dataType, AlertDialog showAlert) {
                        if(theme.type == 1){
                            politicalLevel = theme;
                            tv_political.setText(theme.title);
                        }

                        dismissDialog(showAlert);
                    }
                });
                break;
            case R.id.tv_job:
                PopuTypeSelectState.setShowData(this,jobMap, new PopuTypeSelectState.OnAlertOnClick() {
                    @Override
                    public void onClick(Base theme, int dataType, AlertDialog showAlert) {
                        if(theme.type == 1){
                            jobLevel = theme;
                            tv_job.setText(theme.title);
                        }

                        dismissDialog(showAlert);
                    }
                });
                break;
            case R.id.send_discuss:
                if(et_name.getText().toString().isEmpty()){
                    PromptManager.showToast("姓名不能为空");
                }else if(et_card.getText().toString().isEmpty()){
                    PromptManager.showToast("身份证号不能为空");
                }else if(et_phone.getText().toString().isEmpty()){
                    PromptManager.showToast("手机号不能为空");
                }else if(et_code.getText().toString().isEmpty()){
                    PromptManager.showToast("验证码不能为空");
                }else{
                    if(CommonUtil.isNetWork()) {
                        submit();
                    }else{
                        PromptManager.showToast(R.string.network_error);
                    }
                }
                break;
        }
    }

    /**
     * 提交
     */
    private void submit() {
        if(dialog.isShowing()){
            dialog.dismiss();
        }
        dialog.show();
        if(tranImgs!=null||tranImgs.size()>0){
            dialog.setMessage("上传图片中...");
        HashMap<String,String> mapKeys = new HashMap<String,String>();
        mapKeys.put("module","volunteer-headPhoto");
            //上传图片
            Xutils.UpLoadImgs(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.UPLOAD,
                    mapKeys,
                    tranImgs,
                    new MyCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            super.onSuccess(result);
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String filePath = jsonObject.getString("filePath");
//                                String host = jsonObject.getString("host");
//                                String path = host+filePath;
                                submit(filePath);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            super.onError(ex, isOnCallback);
                            Log.e("error",ex.toString());
                            dialog.dismiss();
                        }
                    });
        }else{
            //直接提交数据
            submit("");
        }
    }

    public void submit(String photo){
        dialog.setMessage("信息提交中...");
        Log.e("photo",photo+"");
        HashMap<String,String> fMapKeys = new HashMap<String,String>();
        fMapKeys.put("name",et_name.getText().toString());
        fMapKeys.put("photo",photo);
        if(rg.getCheckedRadioButtonId()==R.id.rb_man){
            fMapKeys.put("sex","0");
        }else{
            fMapKeys.put("sex","1");
        }
        fMapKeys.put("birth_day",tv_time.getText().toString());
        fMapKeys.put("idcard",et_card.getText().toString());
        fMapKeys.put("mobile",et_phone.getText().toString());
        fMapKeys.put("sms_code",et_code.getText().toString());
        fMapKeys.put("email",et_mail.getText().toString());
        String political="";
        String str = tv_political.getText().toString();
        for (Base base : politicalMap){
            if(base.title.equals(str)){
                political = base.id+"";
                break;
            }
        }
        fMapKeys.put("political",political);
        String education="";
        str = tv_education.getText().toString();
        for (Base base : eduMap){
            if(base.title.equals(str)){
                education = base.id+"";
                break;
            }
        }
        fMapKeys.put("education",education);
        String job="";
        str = tv_job.getText().toString();
        for (Base base : jobMap){
            if(base.title.equals(str)){
                job = base.id+"";
                break;
            }
        }
        fMapKeys.put("profession",job);
        if(rg_type.getCheckedRadioButtonId()==R.id.rb_gr){
            fMapKeys.put("type","0");
        }else{
            fMapKeys.put("type","1");
        }
        fMapKeys.put("address",et_adr.getText().toString());
        fMapKeys.put("art_spetiality",et_hoby.getText().toString());
        fMapKeys.put("content",et_content.getText().toString());
        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.VOLUNTEER_SUBMIT,
                fMapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        dialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            int status = jsonObject.getInt("status");
                            if(status==0){
                                PromptManager.showToast("提交成功!");
                                finish();
                            }else{
                                String statusText = jsonObject.getString("statusText");
                                PromptManager.showToast(statusText);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        dialog.dismiss();
                        PromptManager.showToast("提交失败!");
                    }
                });
    }
    /**
     *头像处理
     */
    private void addPath() {
        Intent intent = new Intent(this, ImagesSelectorActivity.class);
        intent.putExtra(SelectorSettings.SELECTOR_MAX_IMAGE_NUMBER, 1);
        intent.putExtra(SelectorSettings.SELECTOR_MIN_IMAGE_SIZE, 100000);
        intent.putExtra(SelectorSettings.SELECTOR_SHOW_CAMERA, true);
        intent.putStringArrayListExtra(SelectorSettings.SELECTOR_INITIAL_SELECTED_LIST, (ArrayList<String>) tranImgs);
        startActivityForResult(intent, REQUEST_CODE);
    }
    /**
     * 发送短信
     */
    private void sendMsg() {
        String phoneNums = et_phone.getText().toString();
        if (!judgePhoneNums(phoneNums)) {
            PromptManager.showToast(R.string.mobile_phone_format_is_wrong);
            return;
        }

        mapKeys.put(AppHttpKey.MOBILE,phoneNums);
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.SEND_SMS,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            PromptManager.showToast(JSONTool.errorHint(result));
                        }
                    }
                });
    }
    /**
     * 判断手机号码是否合理
     *
     * @param phoneNums
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (CommonUtil.isMatchLength(phoneNums, 11)
                && CommonUtil.isMobileFormatNO(format,phoneNums)) {
            return true;
        }
        PromptManager.showToast(R.string.mobile_phone_format_is_wrong);
        return false;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // get selected images from selector
        if (requestCode == REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                tranImgs = data.getStringArrayListExtra(SelectorSettings.SELECTOR_RESULTS);
                if(isRequestList(tranImgs)){
                    CommonUtil.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            setImgPath("file://"+tranImgs.get(0),iv_head, OptionImageUtils.getPersonIcon());
                        }
                    });
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /******设置时间*******/
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        }
        return null;
    }
    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear + 1;
            mDay = dayOfMonth;
            setRegisTime();
        }
    };
    /**
     * 设置时间
     */
    private void setRegisTime(){
        String time = mYear +"-"+String.format(Locale.CHINA,"%02d", mMonth)+"-"+String.format(Locale.CHINA,"%02d", mDay);
        tv_time.setText(time);
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                tv_code.setText("重新发送(" + i + ")");
            } else if (msg.what == -8) {
                tv_code.setText("获取验证码");
                tv_code.setClickable(true);
                i = 60;
            }
        }
    };
}
